import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../domain/entities/todo.dart';
import '../../../domain/entities/project.dart' show Priority;

/// 待办任务状态
abstract class TodoState {}

class TodoInitial extends TodoState {}

class TodoLoading extends TodoState {}

class TodosLoaded extends TodoState {
  final List<Todo> todos;
  TodosLoaded(this.todos);
}

class TodoLoaded extends TodoState {
  final Todo todo;
  TodoLoaded(this.todo);
}

class TodoError extends TodoState {
  final String message;
  TodoError(this.message);
}

/// 待办任务状态通知器
class TodoStateNotifier extends Notifier<TodoState> {
  @override
  TodoState build() {
    return TodoInitial();
  }

  /// 获取待办任务列表
  Future<void> loadTodos({int? projectId}) async {
    state = TodoLoading();

    try {
      // 模拟数据
      final mockTodos = [
        Todo(
          id: 1,
          projectId: 1,
          projectName: '电商平台优化项目',
          title: '完成用户认证模块',
          description: '实现登录、注册、权限验证等功能',
          status: TodoStatus.inProgress,
          priority: Priority.high,
          todoType: TodoType.develop,
          assigneeName: '张三',
          reporterName: '管理员',
          dueDate: DateTime.now().add(const Duration(days: 3)),
          estimatedHours: 16.0,
          actualHours: 8.0,
          createTime: DateTime.now().subtract(const Duration(days: 2)),
          updateTime: DateTime.now().subtract(const Duration(hours: 1)),
          isNearDeadline: true,
        ),
        Todo(
          id: 2,
          projectId: 1,
          projectName: '电商平台优化项目',
          title: '设计数据库表结构',
          description: '设计用户、项目、待办等核心表结构',
          status: TodoStatus.done,
          priority: Priority.medium,
          todoType: TodoType.document,
          assigneeName: '李四',
          reporterName: '项目经理',
          dueDate: DateTime.now().subtract(const Duration(days: 1)),
          estimatedHours: 8.0,
          actualHours: 6.0,
          createTime: DateTime.now().subtract(const Duration(days: 5)),
          updateTime: DateTime.now().subtract(const Duration(days: 1)),
          isNearDeadline: false,
        ),
        Todo(
          id: 3,
          projectId: 2,
          projectName: '移动应用开发',
          title: '编写API文档',
          description: '编写详细的API接口文档',
          status: TodoStatus.todo,
          priority: Priority.low,
          todoType: TodoType.document,
          assigneeName: '张三',
          reporterName: '技术负责人',
          dueDate: DateTime.now().add(const Duration(days: 7)),
          estimatedHours: 12.0,
          createTime: DateTime.now().subtract(const Duration(days: 1)),
          updateTime: DateTime.now().subtract(const Duration(minutes: 30)),
          isNearDeadline: false,
        ),
        Todo(
          id: 4,
          projectId: 1,
          projectName: '电商平台优化项目',
          title: '性能优化',
          description: '优化系统响应速度',
          status: TodoStatus.blocked,
          priority: Priority.high,
          todoType: TodoType.develop,
          assigneeName: '王五',
          reporterName: '管理员',
          dueDate: DateTime.now().add(const Duration(days: 5)),
          estimatedHours: 24.0,
          actualHours: 4.0,
          createTime: DateTime.now().subtract(const Duration(hours: 12)),
          updateTime: DateTime.now().subtract(const Duration(minutes: 15)),
          isNearDeadline: true,
        ),
      ];

      // 根据项目ID过滤
      final filteredTodos = projectId != null
          ? mockTodos.where((todo) => todo.projectId == projectId).toList()
          : mockTodos;

      state = TodosLoaded(filteredTodos);
    } catch (e) {
      state = TodoError(e.toString());
    }
  }

  /// 获取待办任务详情
  Future<void> loadTodo(int todoId) async {
    state = TodoLoading();

    try {
      final mockTodo = Todo(
        id: todoId,
        projectId: 1,
        projectName: '电商平台优化项目',
        title: '待办任务 #$todoId',
        description: '这是待办任务 #$todoId 的详细描述',
        status: TodoStatus.inProgress,
        priority: Priority.medium,
        todoType: TodoType.develop,
        assigneeName: '张三',
        reporterName: '管理员',
        dueDate: DateTime.now().add(const Duration(days: 3)),
        estimatedHours: 8.0,
        actualHours: 2.0,
        createTime: DateTime.now().subtract(const Duration(days: 1)),
        updateTime: DateTime.now().subtract(const Duration(minutes: 30)),
        isNearDeadline: true,
      );

      state = TodoLoaded(mockTodo);
    } catch (e) {
      state = TodoError(e.toString());
    }
  }

  /// 更新待办任务状态
  Future<void> updateTodoStatus(int todoId, TodoStatus newStatus) async {
    try {
      // TODO: 实现状态更新
      // final todoRepository = _ref.read(todoRepositoryProvider);
      // await todoRepository.updateTodoStatus(todoId, newStatus);

      // 重新加载待办任务列表
      await loadTodos();
    } catch (e) {
      state = TodoError('更新状态失败：${e.toString()}');
    }
  }

  /// 创建待办任务
  Future<void> createTodo(CreateTodoRequest request) async {
    try {
      // TODO: 实现待办任务创建
      // final todoRepository = _ref.read(todoRepositoryProvider);
      // await todoRepository.createTodo(request);

      // 重新加载待办任务列表
      await loadTodos();
    } catch (e) {
      state = TodoError('创建待办任务失败：${e.toString()}');
    }
  }

  /// 更新待办任务
  Future<void> updateTodo(int todoId, UpdateTodoRequest request) async {
    try {
      // TODO: 实现待办任务更新
      // final todoRepository = _ref.read(todoRepositoryProvider);
      // await todoRepository.updateTodo(todoId, request);

      // 重新加载待办任务
      await loadTodo(todoId);
    } catch (e) {
      state = TodoError('更新待办任务失败：${e.toString()}');
    }
  }

  /// 删除待办任务
  Future<void> deleteTodo(int todoId) async {
    try {
      // TODO: 实现待办任务删除
      // final todoRepository = _ref.read(todoRepositoryProvider);
      // await todoRepository.deleteTodo(todoId);

      // 重新加载待办任务列表
      await loadTodos();
    } catch (e) {
      state = TodoError('删除待办任务失败：${e.toString()}');
    }
  }
}

/// 待办任务状态Provider
final todoStateProvider =
    NotifierProvider<TodoStateNotifier, TodoState>(TodoStateNotifier.new);

/// 待办任务列表Provider
final todosProvider = Provider<List<Todo>>((ref) {
  final todoState = ref.watch(todoStateProvider);
  if (todoState is TodosLoaded) {
    return todoState.todos;
  }
  return [];
});

/// 当前待办任务Provider
final currentTodoProvider = Provider<Todo?>((ref) {
  final todoState = ref.watch(todoStateProvider);
  if (todoState is TodoLoaded) {
    return todoState.todo;
  }
  return null;
});

/// 按状态分组的待办任务Provider
final todosByStatusProvider = Provider<Map<TodoStatus, List<Todo>>>((ref) {
  final todos = ref.watch(todosProvider);
  final groupedTodos = <TodoStatus, List<Todo>>{};

  for (final status in TodoStatus.values) {
    groupedTodos[status] =
        todos.where((todo) => todo.status == status).toList();
  }

  return groupedTodos;
});

/// 创建待办任务请求
class CreateTodoRequest {
  final String title;
  final String description;
  final Priority priority;
  final int projectId;
  final int? assigneeId;
  final DateTime? deadline;

  CreateTodoRequest({
    required this.title,
    required this.description,
    required this.priority,
    required this.projectId,
    this.assigneeId,
    this.deadline,
  });
}

/// 更新待办任务请求
class UpdateTodoRequest {
  final String? title;
  final String? description;
  final TodoStatus? status;
  final Priority? priority;
  final int? assigneeId;
  final DateTime? deadline;

  UpdateTodoRequest({
    this.title,
    this.description,
    this.status,
    this.priority,
    this.assigneeId,
    this.deadline,
  });
}
